package com.huilian.iotbox.data.service.impl;

import com.alibaba.fastjson.JSON;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dao.SystemConfigDao;
import com.huilian.iotbox.data.enums.RoleEnum;
import com.huilian.iotbox.data.po.SystemConfig;
import com.huilian.iotbox.data.common.RedisKey;
import com.huilian.iotbox.data.service.SystemConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * @author chenqiwen
 * @CreateDate: 2021-07-12-18-17
 * @Description:
 */
@Slf4j
@Service
public class SystemConfigServiceImpl implements SystemConfigService {

    @Autowired
    private SystemConfigDao systemConfigDao;
    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    @Override
    public synchronized SystemConfig findOneSystemConfigById(int id) {
        Object o = redisCacheTemplate.opsForValue().get(RedisKey.SYSTEM_CONFIG + id);
        SystemConfig systemConfig = (SystemConfig) o;
        if (StringUtils.isEmpty(systemConfig)) {
            systemConfig = systemConfigDao.findOneSystemConfigById(id);
            redisCacheTemplate.opsForValue().set(RedisKey.SYSTEM_CONFIG + id, systemConfig, 1, TimeUnit.HOURS);
        }
        return systemConfig;
    }

    @Override
    public ServerResponse update(SystemConfig systemConfig) {
        if (!systemConfig.getUserInfo().getRoleId().equals(RoleEnum.SUPER_ADMINISTRATOR.getRoleId())) {
            return ServerResponse.createByErrorMessage("你没有权限修改！");
        }
        try {
            systemConfigDao.update(systemConfig);
            redisCacheTemplate.delete(RedisKey.SYSTEM_CONFIG + systemConfig.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
        return ServerResponse.createBySuccess();
    }
}
